package com.example.housekeeping.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@RestController
public class UploadController {
    //@Value的作用是给变量赋值, ${xxx}会去application.properties里面读取配置信息
    @Value("${dirPath}")
    private String dirPath;

    @RequestMapping("/upload")
    public String upload(MultipartFile picFile) throws IOException {
        String fileName = picFile.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        fileName = UUID.randomUUID()+suffix;


        //准备日期相关的路径部分   /2023/02/15/
        SimpleDateFormat format = new SimpleDateFormat("/yyyy/MM/dd/");
        String datePath = format.format(new Date());
        File dirFile = new File(dirPath+datePath);
        if (!dirFile.exists()){
            dirFile.mkdirs();
        }
        String filePath = dirPath+datePath+fileName;
        //保存文件 异常抛出
        picFile.transferTo(new File(filePath));
        // 把日期路径和文件名拼接后响应给客户端   /2023/02/14/xxx.jpg
        return datePath+fileName;
    }

    @RequestMapping("/remove")
    public void remove(String url){
        new File(dirPath+url).delete();
    }
}
